import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { map, filter } from 'rxjs/operators';

import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
import 'dayjs/locale/zh-cn';
import { FormBuilder, Validators } from '@angular/forms';
import { SettingsService, LicenseInfo } from '../../services/settings.service';
import { HttpEventType } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { formGroupToFormData } from 'app/modules/base/helper';
import { ToasterService } from '../../../share/services/toaster.service';
import { LoginService } from '../../../login/services/login.service';
import { MatDialog } from '@angular/material';
dayjs.locale('zh-cn');

@Component({
  selector: 'm-info',
  templateUrl: './info.component.html',
  styleUrls: ['./info.component.scss'],
})
export class InfoComponent implements OnInit {
  sysName: string;
  sysVersion: string;
  picStorage: string; // kb
  upgradeDate = new Date();
  launchDate = new Date();
  launchDays: string;
  adminNum: number;
  msDay: number = 24 * 60 * 60 * 1000;
  licenseInfo$ = this.settingService.licenseInfo$;
  user$ = this.loginService.User$;
  uploadAlertText: string;
  @ViewChild('uploadAlert') uploadAlert: TemplateRef<any>;

  constructor(
    private route: ActivatedRoute,
    private settingService: SettingsService,
    private loginService: LoginService,
    private toaster: ToasterService,
    private dialog: MatDialog,
  ) {}
  fb = new FormBuilder();

  formGroup = this.fb.group({
    // version: ['', Validators.required],
    file: ['', Validators.required],
  });
  profile$ = this.route.data.pipe(map(data => data['profile']));
  progress$ = new BehaviorSubject<number>(0);

  ngOnInit() {
    this.profile$.subscribe(data => {
      this.sysName = data.name;
      this.sysVersion = data.version;
      this.adminNum = data.admin_total;
      this.picStorage = data.picture_space_usage;
      this.upgradeDate = new Date(data.upgraded_at * 1000);
      this.launchDate = new Date(data.launched_at * 1000);
      this.launchDays = dayjs().from(this.launchDate, true);
    });
  }

  upload() {
    const fileControl = this.formGroup.get('file');
    fileControl.setValue(null);
    fileControl.markAsTouched();
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.key';
    input.click();
    input.addEventListener('change', e => {
      fileControl.setValue(input.files[0]), { once: true };
      this.submit();
    });
  }

  async submit() {
    try {
      const payload = formGroupToFormData(this.formGroup);
      new Promise((resolve, reject) => {
        this.settingService
          .licUpload(payload)
          .pipe(
            filter(event => event.type === HttpEventType.UploadProgress),
            map(event => event.loaded / event.total),
          )
          .subscribe(
            v => {
              this.progress$.next(v);
            },
            err => {
              this.uploadAlertText = err.error.error;
              this.dialog.open(this.uploadAlert, { width: '400px' });
            },
            async () => {
              const profile = await this.settingService.get();
              if (
                profile.expired_at === 0 ? false : new Date(profile.expired_at * 1000) < new Date()
              ) {
                this.uploadAlertText = '该授权文件已过期，请重新上传';
                this.dialog.open(this.uploadAlert, { width: '400px' });
              }
              this.settingService.updateLicenseInfo({
                profile,
                showAlert: false,
              });
            },
          );
      }).then();
    } finally {
      this.progress$.next(0);
      console.log('finally');
    }
  }

  onOk() {
    this.dialog.closeAll();
  }
}
